#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int dx[4] = { 1, -1, 0, 0 };
    int dy[4] = { 0, 0, 1, -1 };
    int maxDistance(vector<vector<int>>& grid) {
        int n = grid.size(), m = grid[0].size(), step = 0;
        queue<pair<int, int>> q;
        vector<vector<bool>> map(n, vector<bool>(m, false));
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) if (grid[i][j] == 1) q.push({ i, j }), map[i][j] = true;
        if (q.size() == 0 || q.size() == n * m) return -1;
        while (q.size())
        {
            step++;
            int num = q.size();
            for (int i = 0; i < num; i++)
            {
                auto [x, y] = q.front();
                q.pop();
                for (int k = 0; k < 4; k++)
                {
                    int a = x + dx[k], b = y + dy[k];
                    if (a >= 0 && a < n && b >= 0 && b < m && map[a][b] == false)
                        map[a][b] = true, q.push({ a, b });
                }
            }
        }
        return step - 1;
    }
};